import AMapLoader from '@amap/amap-jsapi-loader';
import { ChangeDetectorRef, Component, Input, OnInit, ViewChild } from '@angular/core';
import { amapConf } from '@conf/amap.config';
import { NzModalRef } from 'ng-zorro-antd/modal';
import { throwError } from 'rxjs';
import { Script } from 'vm';
import { AmapService } from '../amap.service';
declare var AMap: any;
declare var AMapUI: any;
declare var Loca: any;

const CONFIG = amapConf;

@Component({
  selector: 'amap-poi-picker',
  templateUrl: './amap-poi-picker.component.html',
  styleUrls: ['./amap-poi-picker.component.less']
})
export class AmapPoiPickerComponent implements OnInit {
  // @ViewChild('modal')
  // modal: any;
  addressInput: any;

  aMap: any;

  poi: any;
  marker: any;
  infoWindow: any;
  geocoder: any;

  @Input()
  selectedAddress!: string;

  constructor(private modalRef: NzModalRef, private service: AmapService, private cdr: ChangeDetectorRef) {}
  ngOnInit(): void {
    this.mapInit();
    // this.PoiPicker();
  }

  ngOnDestroy(): void {
    if (this.aMap) {
      this.aMap.destroy();
    }
  }

  mapInit() {
    AMapLoader.load({
      // 首次调用 load
      key: CONFIG.key, // 申请好的Web端开发者Key，首次调用 load 时必填
      version: CONFIG.version, // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
      plugins: [
        // 需要使用的的插件列表，如比例尺'AMap.Scale'等
        'AMap.SimpleMarker',
        'AMap.PoiPicker',
        'AMap.Scale',
        'AMap.InfoWindow',
        'AMap.Geolocation',
        'AMap.Geocoder'
      ],
      AMapUI: {
        // 是否加载 AMapUI，缺省不加载
        version: CONFIG.AMapUIVersion, // AMapUI 缺省 1.1
        plugins: ['overlay/SimpleMarker', 'misc/PoiPicker'] // 需要加载的 AMapUI ui插件
      },
      Loca: {
        // 是否加载 Loca， 缺省不加载
        version: CONFIG.LocaVersion // Loca 版本，缺省 1.3.2
      }
    })
      .then(AMap => {
        // 搜索picker
        var poiPicker = new AMapUI.PoiPicker({
          input: 'pickerInput'
        });

        // 地图
        this.aMap = new AMap.Map('modal-container', {
          resizeEnable: true,
          zoom: 16
        });

        // 地图创建成功
        this.aMap.on('complete', () => {
          console.log('地图创建成功');
          this.cdr.detectChanges();
          this.poiPickerReady(poiPicker);
        });

        this.aMap.on('click', (e: any) => {
          this.selectedPOI(e.lnglat);
        });
      })
      .catch(e => {
        throwError(e);
      });
  }

  //POI选点
  poiPickerReady(poiPicker: any) {
    (window as any).poiPicker = poiPicker;
    const map = this.aMap;
    // 定位标志
    this.marker = new AMapUI.SimpleMarker({
      //图标主题
      iconTheme: 'default',
      map: map,
      position: map.getCenter()
    });

    // 信息窗口
    this.infoWindow = new AMap.InfoWindow({
      offset: new AMap.Pixel(0, -20)
    });

    this.geocoder = new AMap.Geocoder({
      city: '010', //城市设为北京，默认：“全国”
      radius: 1000 //范围，默认：500
    });

    if (this.selectedAddress) {
      this.geocoder.getLocation(this.selectedAddress, (status: any, result: any) => {
        if (status === 'complete' && result.info === 'OK') {
          // result中对应详细地理坐标信息
          this.selectedPOI(result.geocodes?.[0].location);
        }
      });
    } else {
      // 获取当前定位
      this.service.getCurrentPosition().subscribe(res => {
        if (res) {
          this.selectedPOI(res.position);
        }
      });
    }

    //选取了某个POI
    poiPicker.on('poiPicked', (poiResult: any) => {
      const source = poiResult.source,
        poi = poiResult.item;

      this.marker.setMap(map);
      this.infoWindow.setMap(map);
      this.selectedPOI(poi.location);
    });
  }

  selectedPOI(location: any) {
    this.marker.setPosition(location);

    this.geocoder.getAddress([location.KL, location.kT], (status: any, result: any) => {
      if (status === 'complete' && result.info === 'OK') {
        // result中对应详细地理坐标信息
        result.regeocode.pois = [location.KL, location.kT];
        this.poi = result.regeocode;
        // console.log(this.poi);
        this.infoWindow.setContent(`地址: <pre>${result.regeocode.formattedAddress}</pre>`);
        this.infoWindow.open(this.aMap, this.marker.getPosition());
        this.infoWindow.setPosition(location);
        this.aMap.setCenter(location);
      }
    });
  }

  closeInfoWindow() {
    this.aMap.clearInfoWindow();
  }

  sure() {
    this.modalRef.destroy();
  }
  cancel() {
    this.modalRef.destroy();
  }
}
